#! /bin/bash

# version 0.9

TEMPSTORAGE ()
{
### ----- temporary storage ----------###

touch \/tmp\/domain
touch \/tmp\/typo3email
base_path=\/srv\/www\/htdocs
adminDBuser="changeme_with_mysql_admin_user"
adminDBpass="changeme_with_mysql_admin_password"
vhostpath=\/etc\/apache2\/vhosts.d
typo3source_path=\/opt\/typo3_4.4.2
domaininfo_path=\/root\/bin\/typo3hosting\/available_domain
drop_location="/typo3_dropped"
host_log=/var/log/apache2/vhost
awstat_cgi_path=/usr/local/awstats/wwwroot/cgi-bin
recipients="user1@mydomain.com, user2@mydomain.com"
}


GetSiteName ()
{
## --------- Get site name ------------- ##

########### site name ##
	echo -e "\tEnter site name without domain. (For mysite.mydomain.com enter only mysite)"
   echo -e "\tEnter nohostname to create site based on domain ( i.e. example.com)...\c"
	read name_site
	
	if [ -z "${name_site}" ]
	 then 
			echo -e "\tcan not be empty...press any key to continue"
			read keypress
			ListHost
	fi
}

DB_CALCULATION ()
{

##--------------create flat DB name from url---------##
echo ${name_domain} > /tmp/domain
part1=`echo $name_site`
part2=`cut -f1 -d '.' /tmp/domain`
part3=`cut -f2 -d '.' /tmp/domain`
db_name=`echo ${part1}_${part2}_${part3}`

db_pass=`< /dev/urandom tr -dc A-Z-0-9_\$\?\@\#\%\*_a-z | head -c8`
#`< /dev/urandom tr -dc A-Z-0-9-a-z | head -c8`
}

mysql_namelength_check ()
{
		  #mysql usrname max 16 characters
		  # check the length

		  if [ `expr length ${part2}${part3}` -gt 16 ]
		  then

					 # extract first 16 characters
					 # expr  string  <start-position>  <length>

					#expr substr ${part2}${part3} 1 16
					#echo " first 16 `expr substr ${part2}${part3} 1 16`"
					#echo " first 8 `expr substr ${part2}${part3} 1 8`"
					# echo " 2nd 8 `expr substr ${part2}${part3} 9 8`"

					 # make part2+part3 = 16
					 part2="`expr substr ${part2}${part3} 1 8`"
					 part3="`expr substr ${part2}${part3} 9 8`"
		  fi
}

mysql_hostname_namelength_check ()
{
        #mysql usrname max 16 characters
        # check the length

             shorter="`expr substr ${name_site} 1 10`"
                
}

CREATEDB ()
{
## ------------ MySql DB creation -------------------##

mysql -u root -p${adminDBpass} -e "create database \`${db_name}\`;"

mysql_namelength_check

#mysql -u root -p${adminDBpass} -e "GRANT INSERT,SELECT,CREATE,UPDATE,INDEX,DELETE,ALTER,DROP ON \
#    ${db_name}.* TO '${name_site}_typo3'@'localhost'  IDENTIFIED BY '${db_pass}';"

if [ "${name_site}" == "nohostname" ]
then
	mysql -u ${adminDBuser} -p${adminDBpass} -e "GRANT INSERT,SELECT,CREATE,UPDATE,INDEX,DELETE,ALTER,DROP ON \
	\`${db_name}\`.* TO '${part2}${part3}'@'localhost'  IDENTIFIED BY '${db_pass}';"

elif [ `expr length ${name_site}_typo3` -gt 10 ]
        then
			
			mysql_hostname_namelength_check
			echo "${shorter}_typo3"
          mysql -u ${adminDBuser} -p${adminDBpass} -e "GRANT INSERT,SELECT,CREATE,UPDATE,INDEX,DELETE,ALTER,DROP ON \
        \`${db_name}\`.* TO '${shorter}_typo3'@'localhost'  IDENTIFIED BY '${db_pass}';"


else
	mysql -u ${adminDBuser} -p${adminDBpass} -e "GRANT 
INSERT,SELECT,CREATE,UPDATE,INDEX,DELETE,ALTER,DROP ON \
	\`${db_name}\`.* TO '${name_site}_typo3'@'localhost'  IDENTIFIED BY '${db_pass}';"
fi

mysql -u root -p${adminDBpass} -e "FLUSH PRIVILEGES;"
###-------insert typo3 database-----------###
mysql -u root -p${adminDBpass}  ${db_name}<${typo3source_path}/typo3_4.4.2.sql

###--------------Change the BE password---------###
 
be_pass=`< /dev/urandom tr -dc A-Z-0-9_\$\?\@\#\%\*_a-z | head -c8`
#`< /dev/urandom tr -dc A-Z-0-9-a-z | head -c8`

if [ "${name_site}" == "nohostname" ]
then
		  mysql -u ${part2}${part3} -p${db_pass} ${db_name}  -e \
		  "update be_users set password=md5('${be_pass}') where username='admin' and password=md5('password');"
else
		  mysql -u ${name_site}_typo3 -p${db_pass} ${db_name}  -e \
		  "update be_users set password=md5('${be_pass}') where username='admin' and password=md5('password');"
fi

###--------------Change BE user-----------------###

#be_user=`< /dev/urandom tr -dc A-Z-0-9_\$\?\@\#\%\*_a-z | head -c5`


#if [ "${name_site}" == "nohostname" ]
#then
#mysql -u ${part2}${part3} -p${db_pass} ${db_name}  -e \
#"update be_users set username='${be_user}' where username='admin' and password=md5('${be_pass}');"


#else
#mysql -u ${name_site}_typo3 -p${db_pass} ${db_name}  -e \
#"update be_users set username='${be_user}' where username='admin' and password=md5('${be_pass}');"
#fi

# OK , make it default admin
#########################################################
}


FTP()
{

##-----------------create ftp account----------------##

## ---------- Random number generator -------------- ##
## ------- c8 for 8 bit long password  --/etc/apache2/vhosts.d------------##
ftp_pass=`< /dev/urandom tr -dc _A-Z-0-9_\$\?\@\#\%\*_a-z | head -c6`
#########################################################

##--------------- Adding into ftp database-----------##

echo ${name_site}.${name_domain} >> /etc/vsftpd/virtual-users.txt
echo $ftp_pass >> /etc/vsftpd/virtual-users.txt

##-----------------create a db format file------------##
db_load -T -t hash -f /etc/vsftpd/virtual-users.txt  /etc/vsftpd/virtual-users.db

##-----------------File permission-----------------##
chmod 600 /etc/vsftpd/virtual-users.db

#-----------------Create virtual user-----------------##

cat >> /etc/vsftpd/vsftpd_user_conf/`echo ${name_site}.${name_domain}` <<EOF
local_root=${base_path}/${name_site}.${name_domain}
local_umask=0022
guest_username=wwwrun
EOF

##----------Reload the server-----------------##
/etc/init.d/vsftpd reload
###########################################################
}


VHOST ()
{
##--------------- create Foler under htdocs ---------##

mkdir ${base_path}/${name_site}.${name_domain}
########################################################
##------------apache vhost configuration------------##

##------------creating the vhost configuration------##

if [ "${name_site}" == "nohostname" ]

then

cat > `echo $vhostpath/${name_site}.${name_domain}`.conf <<EOF

<VirtualHost  ${name_domain}:80>
ServerName http://www.${name_domain}
ServerAlias http://${name_domain}
ServerAdmin joydeep@infoservices.in

#don't loose time with IP address lookups
HostnameLookups Off

# needed for named virtual hosts
#UseCanonicalName Off

DocumentRoot ${base_path}/${name_site}.${name_domain}

DirectoryIndex index.php

ScriptAlias /cgi-bin/ "/srv/www/cgi-bin/"
<Directory "${base_path}/${name_site}.${name_domain}/">

Options +FollowSymLinks -Indexes

# .htaccess slows down apache; only use it when required #
AllowOverride All
Order allow,deny
Allow from all



### Begin: PHP optimisation ###
<IfModule mod_mime.c>
<IfModule mod_php5.c>

		  php_flag display_startup_errors on
		  php_flag display_errors on
		  php_flag html_errors on

		  # The PHP developers recommend disabling this feature. Do that.
		  # It's deprecated and is likely to be unsupported in future versions of PHP.
		  php_flag allow_call_time_pass_reference off

          php_admin_value safe_mode_gid on
          php_admin_value upload_max_filesize 10M
          php_admin_value memory_limit 128M
          php_admin_value max_execution_time 60
          php_flag allow_call_time_pass_reference off
		  # TYPO3 works fine with register_globals turned off.
		  # This is highly recommended!
          php_flag register_globals off
		  # PHP may not declare the argv & argc variables (that would contain the GET
		  # information).
		  # TYPO3 doesn't need this, so just turn it off.
          php_flag register_argc_argv off
		  # Magic quotes for runtime-generated data (data from SQL, exec(), etc.)
          php_flag magic_quotes_gpc off
		  # Order in which PHP registers GET, POST, Cookie and Built-in variables
          php_value variables_order GPCS
 </IfModule>
</IfModule>
### End: PHP optimisation ###



 ### Begin: Rewrite stuff ###
    <IfModule mod_rewrite.c>

        # Enable URL rewriting
         RewriteEngine On
         RewriteBase /
			
			# Stop rewrite processing if we are in the typo3/ directory
			RewriteRule ^(typo3/|t3lib/|tslib/|fileadmin/|typo3conf/|typo3temp/|uploads/|showpic\.php|favicon\.ico) - [L]

			# If the file/symlink/directory does not exist => Redirect to index.php
			# Important note: If you copy/paste this into httpd.conf instead
			# of .htaccess you will need to add '%{DOCUMENT_ROOT}' left to each
			# '%{REQUEST_FILENAME}' part.
			RewriteCond %{REQUEST_FILENAME} !-f
			RewriteCond %{REQUEST_FILENAME} !-d
			RewriteCond %{REQUEST_FILENAME} !-l

			RewriteRule .* index.php [L]

        ### End: Rewrite stuff ###
    </IfModule>
</Directory>

# typo3 exception for mod_security
Include /etc/apache2/typo3_modsecurity.exception
# typo3 file restriction
Include /etc/apache2/typo3_restriction

ScriptAlias /awstats  ${awstat_cgi_path}/awstats.pl
<Location /awstats>
AuthType Basic
AuthName "awstats requires a password"
AuthUserFile ${base_path}/${name_site}.${name_domain}/.htpasswd
Require valid-user
</Location>

</VirtualHost>
EOF

else

cat > `echo $vhostpath/${name_site}.${name_domain}`.conf <<EOF

<VirtualHost  $name_site.${name_domain}:80>
ServerName http://www.${name_site}.${name_domain}
ServerAlias http://${name_site}.${name_domain}
ServerAdmin joydeep@infoservices.in

#don't loose time with IP address lookups
HostnameLookups Off

# needed for named virtual hosts
#UseCanonicalName Off

DocumentRoot ${base_path}/${name_site}.${name_domain}

DirectoryIndex index.php

ScriptAlias /cgi-bin/ "/srv/www/cgi-bin/"
<Directory "${base_path}/${name_site}.${name_domain}/">

Options +FollowSymLinks -Indexes

# .htaccess slows down apache; only use it when required #
AllowOverride All
Order allow,deny
Allow from all



### Begin: PHP optimisation ###
<IfModule mod_mime.c>
<IfModule mod_php5.c>

		  php_flag display_startup_errors on
		  php_flag display_errors on
		  php_flag html_errors on

		  # The PHP developers recommend disabling this feature. Do that.
		  # It's deprecated and is likely to be unsupported in future versions of PHP.
		  php_flag allow_call_time_pass_reference off

          php_admin_value safe_mode_gid on
          php_admin_value upload_max_filesize 10M
          php_admin_value memory_limit 128M
          php_admin_value max_execution_time 60
          php_flag allow_call_time_pass_reference off
		  # TYPO3 works fine with register_globals turned off.
		  # This is highly recommended!
          php_flag register_globals off
		  # PHP may not declare the argv & argc variables (that would contain the GET
		  # information).
		  # TYPO3 doesn't need this, so just turn it off.
          php_flag register_argc_argv off
		  # Magic quotes for runtime-generated data (data from SQL, exec(), etc.)
          php_flag magic_quotes_gpc off
		  # Order in which PHP registers GET, POST, Cookie and Built-in variables
          php_value variables_order GPCS
 </IfModule>
</IfModule>
### End: PHP optimisation ###



 ### Begin: Rewrite stuff ###
    <IfModule mod_rewrite.c>

        # Enable URL rewriting
         RewriteEngine On
         RewriteBase /

			# Stop rewrite processing if we are in the typo3/ directory
			RewriteRule ^(typo3/|t3lib/|tslib/|fileadmin/|typo3conf/|typo3temp/|uploads/|showpic\.php|favicon\.ico) - [L]

			# If the file/symlink/directory does not exist => Redirect to index.php
			# Important note: If you copy/paste this into httpd.conf instead
			# of .htaccess you will need to add '%{DOCUMENT_ROOT}' left to each
			# '%{REQUEST_FILENAME}' part.
			RewriteCond %{REQUEST_FILENAME} !-f
			RewriteCond %{REQUEST_FILENAME} !-d
			RewriteCond %{REQUEST_FILENAME} !-l

			RewriteRule .* index.php [L]

        ### End: Rewrite stuff ###
    </IfModule>
</Directory>

# typo3 exception for mod_security
Include /etc/apache2/typo3_modsecurity.exception
# typo3 file restriction
Include /etc/apache2/typo3_restriction

ScriptAlias /awstats  ${awstat_cgi_path}/awstats.pl
<Location /awstats>
AuthType Basic
AuthName "awstats requires a password"
AuthUserFile ${base_path}/${name_site}.${name_domain}/.htpasswd
Require valid-user
</Location>

</VirtualHost>
EOF

fi

##-------------------reloading apache------------------##
/etc/init.d/apache2 reload

#####################################################################
}

TYPO3()
{
###---------------typo3 installation------------###

cd ${base_path}/${name_site}.${name_domain}
tar -xzf ${typo3source_path}/typo3_src-4.4.2.tar.gz
tar -xzf ${typo3source_path}/dummy-4.4.2.tar.gz
mv dummy-4.4.2/* ./
rm -rf dummy-4.4.2
rm -f typo3_src
ln -s typo3_src-4.4.2 typo3_src

##-----------inserting extension-------------###
###----------phpmyadmin , cooluri, kickstarter -----------###
cp -R ${typo3source_path}/phpmyadmin  ${base_path}/${name_site}.${name_domain}/typo3conf/ext/
cp -R ${typo3source_path}/cooluri  ${base_path}/${name_site}.${name_domain}/typo3conf/ext/
cp -R ${typo3source_path}/kickstarter ${base_path}/${name_site}.${name_domain}/typo3conf/ext/
cp   ${base_path}/${name_site}.${name_domain}/typo3conf/ext/cooluri/cooluri/CoolUriConf.xml_default  ${base_path}/${name_site}.${name_domain}/typo3conf/CoolUriConf.xml

###---------localconf.php modification-----------###

###----go inside typo3conf-------------###
cd ${base_path}/${name_site}.${name_domain}/typo3conf/

## replace in source by -i ##

if [ "${name_site}" == "nohostname" ]
then
sed -i "s/New TYPO3 site/${name_domain}/" localconf.php
else
sed -i "s/New TYPO3 site/${name_site}.${name_domain}/" localconf.php
fi

## delete the line having " default password joh316...##
sed -i '/joh316/d' localconf.php

## delete the line having installToolPassword...##
sed -i '/installToolPassword/d' localconf.php

## generate a 8 bit random password ##
install_pass=`< /dev/urandom tr -dc _A-Z-0-9_\$\?\@\#\%\*_a-z | head -c8`

## Now generate md5 hash on it ##
echo -n "$install_pass" | md5sum  > /tmp/installtool

## delete the - character generated at end ##
sed  -i 's/-//' /tmp/installtool

## delete the blank spaces at the end ##
sed  -i 's/ //g' /tmp/installtool

## now get the string ##
hash=`cat /tmp/installtool`



echo "\$TYPO3_CONF_VARS['BE']['installToolPassword'] = '${hash}';" >> /tmp/typo3configuration
echo "\$typo_db = '${db_name}';" >> /tmp/typo3configuration
if [ "${name_site}" == "nohostname" ]
then
		  echo "\$typo_db_username = '${part2}${part3}';" >> /tmp/typo3configuration

elif [ `expr length ${name_site}_typo3` -gt 10 ]
     then
      mysql_hostname_namelength_check
      echo "\$typo_db_username = '${shorter}_typo3';" >> /tmp/typo3configuration
else
		  echo "\$typo_db_username = '${name_site}_typo3';" >> /tmp/typo3configuration
fi
#echo "\$typo_db_username = '${name_site}_typo3';" >> /tmp/typo3configuration
echo "\$typo_db_password = '${db_pass}';" >> /tmp/typo3configuration
echo "\$typo_db_host = 'localhost'; " >> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['SYS']['encryptionKey'] = '5d06ad0afc9545edc07ad1bb87e8e9c255f84eb11daabca1da9ad1bcc9f870d2ae717599e3a3e44fe737f6b9d2e76b91';" >> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['SYS']['compat_version'] = '4.4';" >> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['GFX']['im_path'] = '/usr/local/typo3sh/IM/bin/';" >> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['GFX']['im_path_lzw'] = '/usr/local/typo3sh/IM/bin/';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['BE']['fileCreateMask'] = '0644';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['BE']['folderCreateMask'] = '0755';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['BE']['createGroup'] = 'www'; ">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['BE']['forceCharset'] = 'utf-8';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['SYS']['setDBinit'] = 'SET NAMES utf8';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['GFX']['im_combine_filename'] = 'combine';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['GFX']['im_version_5'] = '';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['GFX']['im_stripProfileCommand'] =  '';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['GFX']['TTFdpi'] = '92';">> /tmp/typo3configuration
echo "\$TYPO3_CONF_VARS['GFX']['gdlib_2'] = '1';">> /tmp/typo3configuration

echo "\$TYPO3_CONF_VARS['EXT']['extConf']['phpmyadmin'] = 'a:2:{s:12:"hideOtherDBs";s:1:"1";s:9:"uploadDir";s:21:"uploads/tx_phpmyadmin";}';">> /tmp/typo3configuration   
echo "\$TYPO3_CONF_VARS['EXT']['extConf']['cooluri'] = 'a:3:{s:6:"LANGID";s:1:"L";s:7:"XMLPATH";s:25:"typo3conf/CoolUriConf.xml";s:11:"MULTIDOMAIN";s:1:"0";}';">> /tmp/typo3configuration 
###--------insert the above in localconf.php after 3rd line-----###

sed '3r/tmp/typo3configuration' localconf.php > /tmp/localconf.php
mv /tmp/localconf.php ./

###-------Activating the phpmyadmin,cooluri,kickstarter--------------###
sed -i "s/t3skin/t3skin,phpmyadmin,cooluri,kickstarter/" localconf.php

###-----------Enable Install tool---------------###
touch ENABLE_INSTALL_TOOL

###--------set permission--------------###
chown -R wwwrun:www ${base_path}/${name_site}.${name_domain}
chmod 0755 ${base_path}/${name_site}.${name_domain}
#change file permission to 0644
find ${base_path}/${name_site}.${name_domain} -type f   -exec chmod -v 0644 {} \;
#change dir permission to 0755
find ${base_path}/${name_site}.${name_domain} -type d   -exec chmod -v 0755 {} \;
#chown -R wwwrun:www ${base_path}/${name_site}.${name_domain}/typo3conf
#chown -R wwwrun:www ${base_path}/${name_site}.${name_domain}/typo3temp
#chown -R wwwrun:www ${base_path}/${name_site}.${name_domain}/uploads
#chown -R wwwrun:www ${base_path}/${name_site}.${name_domain}/fileadmin

# Removal un-necessary files folders (doc)
find ${base_path}/${name_site}.${name_domain} -name README.txt -exec rm {} \;
find ${base_path}/${name_site}.${name_domain} -name readme.txt -exec rm {} \;
find ${base_path}/${name_site}.${name_domain} -name GPL.txt -exec rm {} \;
find ${base_path}/${name_site}.${name_domain} -name LICENSE.txt -exec rm {} \;
find ${base_path}/${name_site}.${name_domain} -name LICENSE -exec rm {} \;
find ${base_path}/${name_site}.${name_domain} -name RELEASE_NOTES.txt -exec rm {} \;
find ${base_path}/${name_site}.${name_domain} -name INSTALL.txt -exec rm {} \;
find ${base_path}/${name_site}.${name_domain} -name doc -exec rm -r {} \;
find ${base_path}/${name_site}.${name_domain} -name LICENSE -exec rm  {} \;
find ${base_path}/${name_site}.${name_domain} -name README -exec rm  {} \;
find ${base_path}/${name_site}.${name_domain} -name TODO -exec rm  {} \;
find ${base_path}/${name_site}.${name_domain} -name ChangeLog -exec rm  {} \;

###---------.htaccess generator---------------###
###-----------go at the document root-----###
cd ${base_path}/${name_site}.${name_domain}/

cat <<EOF >.htaccess

EOF

### and robots.txt ###
cat <<EOF > robots.txt
# disallow all
User-agent: *
Disallow: /
EOF


########################################################
###############   awstas configuration #################
########################################################

htdocs_path=\\/srv\\/www\\/htdocs
cgidir=\/usr\/local\/awstats\/wwwroot\/cgi-bin

if [ "${name_site}" == "nohostname" ]
then
logpath=\\/var\\/log\\/apache2\\/vhost\\/www.${name_domain}\\/access.log
else
logpath=\\/var\\/log\\/apache2\\/vhost\\/www.${name_site}.${name_domain}\\/access.log
fi

include_config=\\/usr\\/local\\/awstats\\/wwwroot\\/cgi-bin\\/geoip

if [ "${name_site}" == "nohostname" ]
then
cp /usr/etc/awstats/awstats.model.conf \
 ${cgidir}/awstats.${name_domain}.conf
else
cp /usr/etc/awstats/awstats.model.conf \
 ${cgidir}/awstats.${name_site}.${name_domain}.conf
fi

# set SiteDomain
if [ "${name_site}" == "nohostname" ]
then
	sed -i "s/SiteDomain=\"\"/SiteDomain=\"${name_domain}\"/" ${cgidir}/awstats.${name_site}.${name_domain}.conf
else
	sed -i "s/SiteDomain=\"\"/SiteDomain=\"${name_site}.${name_domain}\"/" ${cgidir}/awstats.${name_site}.${name_domain}.conf
fi

# set LogFile
if [ "${name_site}" == "nohostname" ]
then
  sed -i "s/LogFile=\"\/var\/log\/httpd\/mylog\.log/LogFile=\"${logpath}/" ${cgidir}/awstats.${name_domain}.conf
else
  sed -i "s/LogFile=\"\/var\/log\/httpd\/mylog\.log/LogFile=\"${logpath}/" ${cgidir}/awstats.${name_site}.${name_domain}.conf
fi

# DirData="."
sed -i "s/DirData=\"\.\"/DirData=\"${htdocs_path}\/${name_site}.${name_domain}\/usage\"/" ${cgidir}/awstats.${name_site}.${name_domain}.conf

# set include path  #Include ""
# for geoip plugins; other configuration can also be included 
sed -i "s/#Include \"\"/Include \"${include_config}\"/" ${cgidir}/awstats.${name_site}.${name_domain}.conf

# create the uasge directory under vhost
mkdir ${base_path}/${name_site}.${name_domain}/usage
chown -R wwwrun:www ${base_path}/${name_site}.${name_domain}/usage

##########################################################

##############   create .htpasswd    #######################
############################################################
# c > create file; b > read password from command line without promt 
htpasswd2 -bc  ${base_path}/${name_site}.${name_domain}/.htpasswd admin ${be_pass}

}

EMAIL ()
{
##----------- send info through email ------------#

echo -e "\tThis is a system generated email, Don't reply" >>/tmp/typo3email
echo -e "\t***********************************************" >>/tmp/typo3email
echo -e " " >>/tmp/typo3email

if [ "${name_site}" == "nohostname" ]
then

echo -e "\t${name_domain} typo3 access information" >>/tmp/typo3email
echo -e "\t----------------------------------------------------------" >>/tmp/typo3email
echo -e "\turl: http://${name_domain}" >>/tmp/typo3email
echo -e " " >>/tmp/typo3email

else

echo -e "\t$name_site.${name_domain} typo3 access information" >>/tmp/typo3email
echo -e "\t----------------------------------------------------------" >>/tmp/typo3email
echo -e "\turl: http://$name_site.${name_domain}" >>/tmp/typo3email
echo -e " " >>/tmp/typo3email

fi

echo -e "\tError reporting ( for development site )" >>/tmp/typo3email
echo -e "\t-----------------------------------------" >>/tmp/typo3email
echo -e "\thtml_errors:\ton" >>/tmp/typo3email
echo -e "\tphp_errors:\ton" >>/tmp/typo3email
echo -e " " >>/tmp/typo3email

echo -e "\tMysql information" >>/tmp/typo3email
echo -e "\t-----------------------------------------" >>/tmp/typo3email
echo -e "\tMysql DB:\t${db_name}" >>/tmp/typo3email
if [ "${name_site}" == "nohostname" ]
then
		  echo -e "\tMysql user:\t${part2}${part3}" >>/tmp/typo3email
else
		  echo -e "\tMysql user:\t${name_site}_typo3" >>/tmp/typo3email
fi
echo -e "\tMysql password:\t$db_pass" >>/tmp/typo3email
echo -e "\tPhpMyAdmin and cooluri preinstalled\t ">>/tmp/typo3email

echo -e " " >>/tmp/typo3email
echo -e "\tServer PhpMyAdmin link" >>/tmp/typo3email
echo -e "\t-----------------------------------------" >>/tmp/typo3email
echo -e "\thttps://infoservices.in:45/" >>/tmp/typo3email

echo -e " " >>/tmp/typo3email
echo -e "\tftp information" >>/tmp/typo3email
echo -e "\t-----------------------------------------">>/tmp/typo3email
echo -e "\tftp user:\t${name_site}.${name_domain}">>/tmp/typo3email
echo -e "\tftp passwd:\t$ftp_pass">>/tmp/typo3email

if [ "${name_site}" == "nohostname" ]
then
echo -e "\tftp server:\t${name_domain}">>/tmp/typo3email
else
echo -e "\tftp server:\t${name_site}.${name_domain}">>/tmp/typo3email
fi

echo -e "\tftp port:\t60021">>/tmp/typo3email

echo -e " " >>/tmp/typo3email
echo -e "\tTypo3 access" >>/tmp/typo3email
echo -e "\t-----------------------------------------" >>/tmp/typo3email
echo -e "\tInstall tool\t${install_pass}" >>/tmp/typo3email
#echo -e "\tUser Name:\t${be_user}" >>/tmp/typo3email
echo -e "\tUser Name:\tadmin" >>/tmp/typo3email
echo -e "\tPassword:\t${be_pass}" >>/tmp/typo3email

if [ "${name_site}" == "nohostname" ]
then
		  echo -e " " >>/tmp/typo3email
		  echo -e "\tSite Statistic" >>/tmp/typo3email
		  echo -e "\t-----------------------------------------" >>/tmp/typo3email
		  echo -e "\turl:\thttp://${name_domain}/awstats/" >>/tmp/typo3email
		  echo -e "\tUser Name:\tadmin" >>/tmp/typo3email
		  echo -e "\tPassword:\t${be_pass}" >>/tmp/typo3email
else
		  echo -e " " >>/tmp/typo3email
		  echo -e "\tSite Stats" >>/tmp/typo3email
		  echo -e "\t-----------------------------------------" >>/tmp/typo3email
		  echo -e "\turl:\thttp://${name_site}.${name_domain}/awstats/" >>/tmp/typo3email
		  echo -e "\tUser Name:\tadmin" >>/tmp/typo3email
		  echo -e "\tPassword:\t${be_pass}" >>/tmp/typo3email
fi

if [ "${name_site}" == "nohostname" ]
then
mail -r "noreply@infoservices.in" -s "${name_domain} typo3 installation Report" ${recipients} </tmp/typo3email
else
mail -r "noreply@infoservices.in" -s "${name_site}.${name_domain} typo3 installation Report" ${recipients} </tmp/typo3email
fi

## save the email info , used in restore process ##
cat /tmp/typo3email > ${base_path}/${name_site}.${name_domain}/email
## and meke it non readable by appche and ftp ##
chmod 400 ${base_path}/${name_site}.${name_domain}/email
}


RESET ()
{

##-----------------RESET variable---------------##
db_pass=
db_name=
be_pass=
part1=
part2=
part3=
ftp_pass=
name_site=
name_domain=
base_path=
adminDBpass=
vhostpath=
install_pass=
hash=
typo3source_path=
recipients=
QUERY=
domaininfo_path=
drop_location=
Hosting=
Hosting_no_date=
db_username=

###------------remove temporary storage-------------##
rm /tmp/domain 2>/dev/null
rm /tmp/typo3email 2>/dev/null
rm /tmp/typo3configuration 2>/dev/null
rm /tmp/installtool 2>/dev/null
}


CHECK()
{

##-----DB_CALCULATION has to be called before calling this----##
##-----so that it can get the database name ------------------##
 
   breakpoint=0
	
   if [ -d `echo /var/lib/mysql/${db_name}` ]
   then
	    echo -e "\n\t\tDatabase ${db_name} exist"
		breakpoint=1
   fi

   if [ -d `echo ${base_path}/${name_site}.${name_domain}` ]
   then
        echo -e "\n\t\t${base_path}/${name_site}.${name_domain}....typo3 directory exit"
		breakpoint=1   
   fi
   
   if [ -e /etc/vsftpd/vsftpd_user_conf/`echo ${name_site}.${name_domain}` ]
   then 
		echo -e "\n\t\t/etc/vsftpd/vsftpd_user_conf/${name_site}.${name_domain}....ftp configuration exit" 
        breakpoint=1
   fi
   
   if [ -e `echo $vhostpath/${name_site}.${name_domain}`.conf ]
   then
		echo -e "\n\t\t${vhostpath}/${name_site}.${name_domain}.conf... vhost exist"
		breakpoint=1
	fi
	
}

CREATE_CHECK()
{
CHECK

if [ $breakpoint -eq 1 ]
then
	echo -e "\n\t\t\E[31;1mERROR!! FIX MANUALLY\n" ; tput sgr0
	exit
fi
}

DELETE_VHOST()
{
echo -e "\tremoving vhost...."
rm -rvf $vhostpath/${name_site}.${name_domain}.conf
/etc/init.d/apache2 reload
}

DELETE_FTP()
{
echo -e "\tremoving ftp configuration....."

###----removing userid/password from the virtual-users.txt--###
###match the username and the line next as it is the password###
sed -i "/${name_site}.${name_domain}/,+1 d" /etc/vsftpd/virtual-users.txt

###-----remove the configuration file-----###
rm -rvf /etc/vsftpd/vsftpd_user_conf/${name_site}.${name_domain}

# regenaration does not delete the previous information, so delete the database
rm /etc/vsftpd/virtual-users.db

##-----------------create a db format file------------##
db_load -T -t hash -f /etc/vsftpd/virtual-users.txt  /etc/vsftpd/virtual-users.db

##-----------------File permission-----------------##
chmod 600 /etc/vsftpd/virtual-users.db

##----------Reload the server-----------------##
/etc/init.d/vsftpd reload
###########################################################

}

DELETE_DB()
{
echo -e "\removing database...... "
DB_CALCULATION
mysql_namelength_check
mysql -u root -p${adminDBpass} -e "drop database \`${db_name}\`;"

if [ "${name_site}" == "nohostname" ]
then
		  mysql -u ${adminDBuser} -p${adminDBpass} -e "Drop user '${part2}${part3}'@'localhost';"
else
		  mysql -u ${adminDBuser} -p${adminDBpass} -e "Drop user'${name_site}_typo3'@'localhost';"
fi

mysql -u root -p${adminDBpass} -e "FLUSH PRIVILEGES;"
}

DELETE_TYPO3()
{
rm -rvf ${base_path}/${name_site}.${name_domain}
}

DELETE_TYPO3()
{
rm -rvf ${base_path}/${name_site}.${name_domain}
}

BACKUP()
{
## Put this inside DELETE ##
## This takes backup of the installation to delete ##

#### Today's date ###########
NOW=`date +"%d-%m-%Y"`

## create the folder in backup location ##
mkdir ${drop_location}/${name_site}.${name_domain}_${NOW}

## Mysql dump ##
mysqldump -u root -p${adminDBpass} ${db_name} > ${drop_location}/${name_site}.${name_domain}_$NOW/mysql.${db_name}

## vhost backup ##
cp $vhostpath/${name_site}.${name_domain}.conf  ${drop_location}/${name_site}.${name_domain}_$NOW/vhost.${name_site}.${name_domain}.conf

## backup awstat configuration for vhost ###
mv ${awstat_cgi_path}/awstats.${name_site}.${name_domain}.conf ${drop_location}/${name_site}.${name_domain}_$NOW/

## vlogger log backup ##
mv ${vhost_log}/www.${name_site}.${name_domain}  ${drop_location}/${name_site}.${name_domain}_$NOW/

## Typo3 backup ##
cp -R ${base_path}/${name_site}.${name_domain}  ${drop_location}/${name_site}.${name_domain}_$NOW/

## FTP backup ##
## save ftp host configuration ##
cp /etc/vsftpd/vsftpd_user_conf/${name_site}.${name_domain}  ${drop_location}/${name_site}.${name_domain}_$NOW/vsftp.${name_site}.${name_domain}
## save userid/password ##
sed  -n "/${name_site}.${name_domain}/,+1 p" /etc/vsftpd/virtual-users.txt >  ${drop_location}/${name_site}.${name_domain}_$NOW/ftpuser

cd ${drop_location}/

tar -cjf ${name_site}.${name_domain}_${NOW}_tbz2  ${name_site}.${name_domain}_$NOW
rm -r ${name_site}.${name_domain}_$NOW

cd ..
}

DELETE()
{

CHECK

##-----DB_CALCULATION has to be called before calling this----##
##-----so that it can get the database name ------------------##


if [ $breakpoint -eq 0 ]
then
	echo -e "\n\t\t\E[31;1mNOTHING TO DELETE\n" ; tput sgr0
	exit
fi
	

echo -e "\t\E[31;1mThere is no way to retrieve data after this point [ y/n]...\c" ; tput sgr0
read del
if [ "$del" = Y ] || [ "$del" = y ]
then
	   BACKUP
	   if [ -d `echo /var/lib/mysql/${db_name}` ]
	   then
			echo -e "\n\t\t\E[32;1mDeleting Database ${db_name}"; tput sgr0
			DELETE_DB 1>/dev/null
		else
			echo -e "\n\t\t\E[31;1mDatabase ${db_name} does not exist"; tput sgr0 
	   fi

	   if [ -d `echo ${base_path}/${name_site}.${name_domain}` ]
	   then
			echo -e "\n\t\t\E[32;1mDeleting ${base_path}/${name_site}.${name_domain}" ; tput sgr0
			DELETE_TYPO3  1>/dev/null
	   else
			echo -e "\n\t\t\E[31;1m${base_path}/${name_site}.${name_domain}....typo3 directory does not exit";tput sgr0
	   fi
	   
	   if [ -e /etc/vsftpd/vsftpd_user_conf/`echo ${name_site}.${name_domain}` ]
	   then 
			echo -e "\n\t\t\E[32;1mDeleting /etc/vsftpd/vsftpd_user_conf/${name_site}.${name_domain}" ; tput sgr0
			DELETE_FTP 1>/dev/null
	   else
			echo -e "\n\t\t\E[31;1m/etc/vsftpd/vsftpd_user_conf/${name_site}.${name_domain}....ftp configuration does not exit";tput sgr0
	   fi
	   
	   if [ -e `echo $vhostpath/${name_site}.${name_domain}`.conf ]
	   then
			echo -e "\n\t\t\E[32;1mDeleting ${vhostpath}/${name_site}.${name_domain}.conf" ; tput sgr0
			DELETE_VHOST 1>/dev/null
	   else
			echo -e "\n\t\t\E[31;1m${vhostpath}/${name_site}.${name_domain}.conf... vhost does not exist" ;tput sgr0
	   fi
	   
	   
fi
}

DELETE_EMAIL()
{
echo -e "\t${name_site}.${name_domain} Deleted\n\tThanks for making a clean Server"	> /tmp/typo3email
mail -r "noreply@infoservices.in" -s "${name_site}.${name_domain} typo3 installation Deleted" ${recipients} < /tmp/typo3email
}

doTheMath()
{
	COUNTER=1
	unset DB
   for i in ${QUERY}; do
      DB[$COUNTER]=$i
      COUNTER=`expr $COUNTER + 1`
   done
   height=${#DB[@]}
   for i in $(seq 1 $height); do
      if [ -n "${DB[$i]}" ]; then
         echo "$i. ${DB[$i]}"
      fi
        done
}

ListDomain()
{
clear
### List name_domain name ###########
QUERY=`ls ${domaininfo_path} | xargs -n1 basename`

echo "+--------------------------+"
echo "| Listing all  domain      |"
echo "+--------------------------+"
doTheMath
echo " "
echo -e "\E[32;2m   => Select the Domain to create a host" ; tput sgr0
echo " "
echo -e "\E[32;2mQ  => Quit" ; tput sgr0
echo -en "\t\t\t=> "
getListInput
name_domain="${DB[$keypress]}"
ListHost
}

ListHost()
{
clear
### List site name ###########
QUERY=`ls -d  ${base_path}/*.${name_domain}/typo3conf 2>/dev/null | cut -d "/" -f5  2>/dev/null`

echo "+--------------------------------------------------+"
echo    Listing all ${name_domain} TYPO3 hosting
echo "+--------------------------------------------------+"
#doTheMath

doTheMath > /tmp/installation
paste -s -d '\t\t\n'  /tmp/installation

echo " "
echo -e "\E[32;2mA. => Add new site in $name_domain" ; tput sgr0
echo " "
echo -e "\E[32;2m   => Select the Host to Delete" ; tput sgr0
echo " "
echo -e "\E[32;2mM. => Main menu" ; tput sgr0
echo " "
echo -e "\E[32;2mR  => Restore" ; tput sgr0
echo " "
echo -e "\E[32;2mQ  => Quit" ; tput sgr0
echo -en "\t\t\t=> "
getListInput
Hosting="${DB[$keypress]}"
#echo ${DB[$keypress]}
HostManagement
}

ListDropped()
{
QUERY=`ls -d ${drop_location}/*.${name_domain}* 2>/dev/null | xargs -n1 basename  2>/dev/null`
### List the dropped installation ###

echo "+--------------------------------------------------+"
echo    Listing all dropped ${name_domain} hosting
echo "+--------------------------------------------------+"
doTheMath
echo " "
echo -e "\E[32;2m   => Select the Host to Restore" ; tput sgr0
echo " "
echo -e "\E[32;2mM. => Main menu" ; tput sgr0
echo " "
echo -e "\E[32;2mQ  => Quit" ; tput sgr0
echo -en "\t\t\t=> "
getListInput
Hosting="${DB[$keypress]}"

echo -e "\E[31;1m => Restore $Hosting.....[y/n]" ; tput sgr0
echo " "
echo -e "\E[32;2m  => Any key to host listing" ; tput sgr0
echo " "
echo -en "\t\t\t=> "

read keypress
if [ "${keypress}" = "y" ] || [ "${keypress}" = "Y" ]
	then 
	  RESTORE;EMAIL_RESTORE
	  
fi

ListHost
}

RESTORE()
{
cd ${drop_location}/
tar -xjf ${Hosting}
## extract name without bz2 ##
Hosting=`ls ${Hosting} | cut -d "_" -f3 --complement`
## extract name without date##
Hosting_no_date=`echo ${Hosting} | cut -d "_" -f1`


## mysql restore ##
###################

# tail -n1  to match the first pattern from last of the file 
db_name=`grep -w "typo_db"  ${drop_location}/${Hosting}/${Hosting_no_date}/typo3conf/localconf.php|tail -n1| cut -d "'" -f2`
db_pass=`grep -w "typo_db_password"  ${drop_location}/${Hosting}/${Hosting_no_date}/typo3conf/localconf.php|tail -n1| cut -d "'" -f2`
db_username=`grep -w "typo_db_username"  ${drop_location}/${Hosting}/${Hosting_no_date}/typo3conf/localconf.php|tail -n1|cut -d "'" -f2`

sleep 5
mysql -u root -p${adminDBpass} -e "create database ${db_name};"
    
mysql -u root -p${adminDBpass} -e "GRANT INSERT,SELECT,CREATE,UPDATE,INDEX,DELETE,ALTER,DROP ON \
    ${db_name}.* TO '${db_username}'@'localhost'  IDENTIFIED BY '${db_pass}';"
    
mysql -u root -p${adminDBpass} -e "FLUSH PRIVILEGES;"

##Insert the DB ##
mysql -u root -p${adminDBpass} ${db_name} < ${drop_location}/${Hosting}/mysql.${db_name}

## typo3 restore ##
###################
chown -R wwwrun:www ${drop_location}/${Hosting}/${Hosting_no_date}
mv ${drop_location}/${Hosting}/${Hosting_no_date}  /${base_path}/

## vhost Restore ##
###################
mv  ${drop_location}/${Hosting}/vhost.${Hosting_no_date}.conf $vhostpath/${Hosting_no_date}.conf

## awstat config  restore ##
#############################
mv ${drop_location}/${Hosting}/awstats.${name_site}.${name_domain}.conf ${awstat_cgi_path}/

## vlogger log restore ##
#########################
chown -R wwwrun:www  ${drop_location}/${Hosting}/www.${name_site}.${name_domain}
mv ${drop_location}/${Hosting}/www.${name_site}.${name_domain} ${vhost_log}/

##-------------------reloading apache------------------##
/etc/init.d/apache2 reload

## FTP restore ##
#################
mv ${drop_location}/${Hosting}/vsftp.${Hosting_no_date}  /etc/vsftpd/vsftpd_user_conf/${Hosting_no_date}

##--------------- Adding into ftp database-----------##

cat ${drop_location}/${Hosting}/ftpuser >> /etc/vsftpd/virtual-users.txt

##-----------------create a db format file------------##
db_load -T -t hash -f /etc/vsftpd/virtual-users.txt  /etc/vsftpd/virtual-users.db

##-----------------File permission-----------------##
chmod 600 /etc/vsftpd/virtual-users.db

##----------Reload the server-----------------##
/etc/init.d/vsftpd reload

##Delete the uncompress folder##
################################
## remove both folder and tbz2 #
rm -r ${drop_location}/${Hosting}*

}


EMAIL_RESTORE()
{
##---- send email with access info---###
mail -r "noreply@infoservices.in" -s "${Hosting_no_date} typo3 installation Restored" ${recipients} \
 < ${base_path}/${Hosting_no_date}/email
}


ftp_migration_mr()
{
TIME=`date +"%d-%m-%Y-%T"`
##---- migration from this server to remote server through ftp ---- ##

##--- changed path to the local typo3 installation ---##
cd  ${base_path}/${Hosting}

echo -e "This option migrate fileadmin, uploads and ext"
echo -e "************************************************\n"

echo -e "ftp server name or ip......\c"
read ftp_server

echo -e "ftp user name......\c"
read ftp_user

echo -e "ftp password......\c"
read ftp_passwd

echo -e "ftp path where typo3 wiil be installed,Press [ enter] for /"
read ftp_path
if [ -z $ftp_path ]
then
ftp_path="/"
fi

echo -e "Adjust the database info in localconf before uploading"
echo -e "Enter remote databas name.....\c"
read remote_db
echo -e "Enter remote databas username.....\c"
read remote_db_username
echo -e "Enter remote databas password.....\c"
read remote_db_passwd

##-- Adjust the database info in localconf before uploading --#
##-- So that our localconf.php communicate with the remote DB--#
cp ${base_path}/${Hosting}/typo3conf/localconf.php /tmp

## delete the lines having database info

sed -i '/typo_db_username/d' /tmp/localconf.php
sed -i '/typo_db_password/d' /tmp/localconf.php
sed -i '/typo_db/d' /tmp/localconf.php

## Now insert the modified info ##
echo "\$typo_db = '${remote_db}';" >> /tmp/localconf.php
echo "\$typo_db_username = '${remote_db_username}';" >> /tmp/localconf.php
echo "\$typo_db_password = '${remote_db_passwd}';" >> /tmp/localconf.php

echo -e "complete typo3 migration .......?[y/n]"
echo -e "Hint: complete (along with souce) is needed if there is no pre existing typo3 installation"
echo -e "If typo3 is already there then copy only fileadmin, ext, uploads etc"

read installmode

if [ "${installmode}" = "y" ] || [ "${installmode}" = "Y" ]
	then 
		lftp -u ${ftp_user},${ftp_passwd} ${ftp_server} -e \
		"cd ${ftp_path};\
		 mirror -R fileadmin;\
		 mirror -R uploads;\
		 mirror -R typo3;\
		 mirror -R typo3_src;\
		 mirror -R typo3conf;\
		 put /tmp/localconf.php typo3conf/ ;\
		 mirror -R typo3temp;\
		 mirror -R t3lib;\
		 put index.php;\
		 put clear.gif;\
		 exit"
		
		
	else
		## create the backup first then upload##
		lftp -u ${ftp_user},${ftp_passwd} ${ftp_server} -e \
		"cd ${ftp_path};\
		 mv fileadmin fileadmin_${TIME} ;\
		 mv uploads uploads_${TIME} ;\
		 mv typo3conf/ext typo3conf/ext_${TIME};\
		 mv typo3conf/localconf.php typo3conf/localconf.php_${TIME} ;\
		 mirror -R fileadmin;\
		 mirror -R uploads;\
		 mirror -R typo3conf/ext typo3conf/ ;\
		 put /tmp/localconf.php typo3conf/ ;\
	    put typo3conf/realurlconf.php typo3conf/ ;\
		 put typo3conf/CoolUriConf.xml typo3conf/ ;\
		 exit"
fi

## delete the /tmp/localconf.php ##
rm /tmp/localconf.php
}

ssh_migration_mt ()
{

##---- migration from remote server to this server ---- ##

echo -e "This option migrate fileadmin, uploads and ext along with mysql"
echo -e "*****************************************************************\n"

echo -e "ssh server name or ip, enter for default (myserver)......\c"
read ssh_server
if [ -z $ssh_server ]
then
ssh_server=officeserver.selfip.org
fi

echo -e "ssh user name, enter for default (myserver)......\c"
read ssh_user
if [ -z $ssh_user ]
then
ssh_user=root
fi

echo -e "ssh server port, enter for default(22)..\c"
read ssh_port
if [ -z $ssh_port ]
then
ssh_port=22
fi

echo -e "absolute source path..\c"
read ssh_path

echo -e "MySql user name, enter for default (myserver)..\c"
read ssh_mysql_user
if [ -z $ssh_mysql_user ]
then
ssh_mysql_user=root
fi

echo -e "MySql user password, enter for default (myserver)..\c"
read ssh_mysql_pass
if [ -z $ssh_mysql_pass ]
then
ssh_mysql_pass=infoservices
fi

echo -e "MySql hostname, enter for localhost ..\c"
read ssh_mysql_hostname

if [ -z $ssh_mysql_hostname ]
then
ssh_mysql_hostname=localhost
fi

echo -e "MySql DBNAME ..\c"
read ssh_mysql_db

## temporary storage location in remote server ##
temp_storage=/tmp/typo3_migration

echo -e "going to ssh-login, you need to provide password"

# copy files from remote server #
# -t Allocates a terminal device to the process, needed to provide password to scp #

ssh -t -p ${ssh_port} ${ssh_user}@${ssh_server} \
	"rm -rf ${temp_storage}*;\
	 mkdir ${temp_storage};\
	 cp -R ${ssh_path}/fileadmin ${temp_storage};\
	 cp -R ${ssh_path}/uploads ${temp_storage};\
	 cp -R ${ssh_path}/typo3conf/ext ${temp_storage};\
	 cp ${ssh_path}/typo3conf/realurlconf.php ${temp_storage}/ ;\
	 cp ${ssh_path}/typo3conf/CoolUriConf.xml ${temp_storage}/ ;\
	 mysqldump -u ${ssh_mysql_user} -p${ssh_mysql_pass} -h ${ssh_mysql_hostname} ${ssh_mysql_db} > ${temp_storage}/MYSQL;\
	 cd /tmp;\
	 tar -cvjf  typo3_migration.tbz2  typo3_migration;\
	 echo -e "Files are coming to this server by scp, you need to provide backup user password, as ssh root login disable here "
	 echo -e "*****************************************************************************************************************\n"
	 scp -P 47015 typo3_migration.tbz2 backup@infoservices.in:/tmp/ ;\
	 rm -rf typo3_migration*;\
	 exit"
	 
## unpack ##
## use the same storage location in this server ##
cd /tmp
tar -xvjf  typo3_migration.tbz2

## backup existing fileadmin, uploads, ext etc...##
TIME=`date +"%d-%m-%Y-%T"`
cd ${base_path}/${Hosting}
mv fileadmin fileadmin_${TIME}
mv uploads uploads_${TIME}
mv typo3conf/ext typo3conf/ext_${TIME}

## Now copy from the downloaded ##
mv ${temp_storage}/fileadmin  ${base_path}/${Hosting}
mv ${temp_storage}/uploads  ${base_path}/${Hosting}
mv ${temp_storage}/ext  ${base_path}/${Hosting}/typo3conf/
mv ${temp_storage}/realurlconf.php  ${base_path}/${Hosting}/typo3conf/  # if any ##
mv ${temp_storage}/CoolUriConf.xml  ${base_path}/${Hosting}/typo3conf/  # if any ##

## set permision ##
chown -R wwwrun:www ${base_path}/${Hosting}/typo3conf
chown -R wwwrun:www ${base_path}/${Hosting}/typo3temp
chown -R wwwrun:www ${base_path}/${Hosting}/uploads
chown -R wwwrun:www ${base_path}/${Hosting}/fileadmin

#change file permission to 0644
find ${base_path}/${Hosting} -type f   -exec chmod -v 0644 {} \;
#change dir permission to 0755
find ${base_path}/${Hosting} -type d   -exec chmod -v 0755 {} \;

# Removal un-necessary files folders (doc)
find ${base_path}/${Hosting} -name README.txt -exec rm {} \;
find ${base_path}/${Hosting} -name README -exec rm {} \;
find ${base_path}/${Hosting} -name readme.txt -exec rm {} \;
find ${base_path}/${Hosting} -name readme -exec rm {} \;
find ${base_path}/${Hosting} -name GPL.txt -exec rm {} \;
find ${base_path}/${Hosting} -name LICENSE.txt -exec rm {} \;
find ${base_path}/${Hosting} -name LICENSE -exec rm {} \;
find ${base_path}/${Hosting} -name TODO -exec rm {} \;
find ${base_path}/${Hosting} -name RELEASE_NOTES.txt -exec rm {} \;
find ${base_path}/${Hosting} -name INSTALL.txt -exec rm {} \;
find ${base_path}/${Hosting} -name doc -exec rm -r {} \;
# Remove .svn if exist
find ${base_path}/${Hosting} -name .svn  -exec rm -r {} \;

## mysql migration ##

DB_CALCULATION

#echo -e "speaking url modification"
#echo -e "press enter to bypass or anything else to enter the configuration part"
#read keypress
#if [ -z $keypress ]
#then
#	echo -e "Bypassing speaking url"
#else
#	echo -e "Local server realurl path is 192.168.1.1/<website-folder>"
#	echo -e "Enter Local server folderanme where the site is running.....\c"
#	read websiteFolder

#	if [ "${name_site}" == "nohostname" ]
#	then
#	sed -i "s/192.168.1.1\/${websiteFolder}/${name_domain}/"  ${temp_storage}/MYSQL
#	else
#	sed -i "s/192.168.1.1\/${websiteFolder}/${name_site}.${name_domain}/"  ${temp_storage}/MYSQL
#	fi
#fi

mysql -u ${adminDBuser} -p${adminDBpass} ${db_name} < ${temp_storage}/MYSQL

## Reset typo3 BE password ##
echo -e "Enter typo3 BE password....\c"
read be_pass
mysql  -u ${adminDBuser} -p${adminDBpass} ${db_name}  -e \
"update be_users set password=md5('${be_pass}') where username='admin' ;"

## Reset typo3 BE username ##
echo -e "Enter typo3 BE username....\c"
read be_user
mysql  -u ${adminDBuser} -p${adminDBpass} ${db_name}  -e \
"update be_users set username='${be_user}' where username='admin' and password=md5('${be_pass}');"

## remove the downloaded folders from /tmp
cd /tmp
rm -rf typo3_migration*

## call svn cleanup ##
svn_cleanup

echo -e "Remember to enable additional extension from BE"

sleep 6
}

HostManagement ()
{
echo -e "\E[31;1mD => Delete $Hosting" ; tput sgr0
echo " "
echo -e "\E[32;2mMT=> SSH migration from remote --> this server" ; tput sgr0
echo " "
echo -e "\E[32;2mFTP=> ftp migration this server --> remote" ; tput sgr0
echo " "
echo -e "\E[32;2m  => Any key to host listing" ; tput sgr0
echo " "
echo -en "\t\t\t=> "

read keypress
if [ "${keypress}" = "d" ] || [ "${keypress}" = "D" ]
				then 
					 ### extract sitename first ###
					 echo ${Hosting} > /tmp/domain
					 name_site=`cut -f1 -d '.' /tmp/domain`
					 DB_CALCULATION;DELETE;DELETE_EMAIL





elif [ "${keypress}" = "ftp" ] || [ "${keypress}" = "FTP" ]
				then 
					### extract sitename first ###
					 echo ${Hosting} > /tmp/domain
					 name_site=`cut -f1 -d '.' /tmp/domain`
					 ftp_migration_mr


elif [ "${keypress}" = "MT" ] || [ "${keypress}" = "mt" ]
				then 
				     ### extract sitename first ###
					 echo ${Hosting} > /tmp/domain
					 name_site=`cut -f1 -d '.' /tmp/domain`
					 ssh_migration_mt
fi

ListHost
}

svn_cleanup()
{
#cleaning .svn folders
find ${base_path}/${Hosting}  -name .svn -exec rm -r {} \;
}

getListInput () 
{
	while read keypress; do
		if [ "${keypress}" = "q" ] || [ "${keypress}" = "Q" ]
			then RESET;exit;
		elif [ "${keypress}" = "m" ] || [ "${keypress}" = "M" ]
			 then clear;ListDomain;
		elif [ "${keypress}" = "a" ] || [ "${keypress}" = "A" ]
				then GetSiteName;DB_CALCULATION;CREATE_CHECK;FTP;CREATEDB;VHOST;TYPO3;EMAIL;ListHost
		elif [ "${keypress}" = "r" ] || [ "${keypress}" = "R" ]
				then	ListDropped	
		elif [ -n "${keypress}" ] && [ "${keypress}" -eq "${keypress}" > /dev/null 2>&1 ] && (("${keypress}" >= "1")) && (("${keypress}" <= $height))
				then 	break
		elif [ -z "${keypress}" ]
			then 
			echo -e "\tcan not be empty"
			getListInput
 		else echo -e "\tInvalid input"
		fi
	done
}

RESET
TEMPSTORAGE	
ListDomain
